import { extendApi } from '@inbiz/utils';
import type { IProps } from './index';
import { formatTreeData, updateTreeData, findTreeNode, findTreeNodes, ITreeData } from './utils';
export default extendApi(
  (
    _events: any,
    props: IProps,
    {
      treeDataRef,
      $treeData,
      checkStrictly,
      checkedKeys,
      showTreeNameKey,
      treeNodeId,
      treeShowNodeId,
      treeNodeParentId,
      treeShowNodeParentId,
      setSelectNode,
      currentKey,
      $currentKey,
      setCheckedKeys,
      $expandedKeys,
      $checkedKeys,
      onRefresh
    },
  ) => {
    return {
      getBusinessData: () => {
        return props.businessData;
      },
      getData: () => {
        return treeDataRef.current;
      },
      loadData: (tree: ITreeData, key?: string) => {
        if (tree) {
          if (key) {
            $treeData((origin: any) => {
              return updateTreeData({
                treeData: origin,
                type: 'add',
                keyValue: key,
                data: formatTreeData({
                  data: tree,
                  key: treeShowNodeId,
                  title: showTreeNameKey,
                  childrenKey: 'child',
                  treeNodeId: [treeNodeId, treeShowNodeId],
                  treeNodeParentId: [treeNodeParentId, treeShowNodeParentId],
                  format: (data) => {
                    data.key = data?.key?.toString();
                  },
                }),
              });
            });
          } else {
            $treeData(
              formatTreeData({
                data: tree,
                key: treeShowNodeId,
                title: showTreeNameKey,
                childrenKey: 'child',
                treeNodeId: [treeNodeId, treeShowNodeId],
                treeNodeParentId: [treeNodeParentId, treeShowNodeParentId],
                format: (data) => {
                  data.key = data?.key?.toString();
                },
              }),
            );
          }
        } else {
          return treeDataRef.current;
        }
      },
      onReload:(key?:string)=>{
        onRefresh(key)
      },
      setSelect: async (id: string, stauts: boolean) => {
        if (stauts) {
          return setSelectNode(id).then(
            () => true,
            (e: any) => {
              console.error(e);
              return false;
            },
          );
        } else {
          if (currentKey?.[0] == id) {
            $currentKey([]);
            return true;
          } else {
            return false;
          }
        }
      },
      getSelect: () => {
        return [findTreeNode({ keyValue: currentKey[0], treeData: treeDataRef.current })];
      },
      getChecked: () => {
        const checked = checkedKeys?.checked || [];
        return findTreeNodes({ keyValue: checked, treeData: treeDataRef.current });
      },
      setChecked: (ids: string[]) => {
        if (checkStrictly) {
          ids.forEach(async (id) => {
            await setSelectNode(id, false);
          });
        } else {
          console.warn('非完全受控状态下设置选中值, 只能是已经加载完成的数据，否则会出错');
        }
        setCheckedKeys(ids);
      },
      expand: (key: string | string[]) => {
        const expandKeys = Array.isArray(key) ? key : [key];
        $expandedKeys((keys: any) => [...new Set([...keys, ...expandKeys])]);
      },
      collapse: (key: string | string[]) => {
        const isArray = Array.isArray(key);
        $expandedKeys((keys: string[]) => {
          return keys.filter((item) => {
            if (isArray) {
              return !key.includes(item);
            } else {
              return item != key;
            }
          });
        });
      },
      setCheckedKeys: (data: object) => {
        // 直接修改antd数据
        $checkedKeys(data);
      },
    };
  },
);
